package TrabalhoP2P;
//servidor

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;

public class TCPServer {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        String clientSentence;
        String nickName = "";
        Boolean closed = false;
        ArrayList<Peer> activedPeers = new ArrayList<Peer>();
        ServerSocket welcomeSocket = new ServerSocket(6789);
        while (true) {
            Socket connectionSocket = welcomeSocket.accept();
            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            InetAddress ip = connectionSocket.getInetAddress();
            closed = false;
            do {
                try {
                    clientSentence = inFromClient.readLine();
                } catch (IOException e) {
                    connectionSocket.close();
                    closed = true;
                    throw e;
                }
                if (clientSentence == null || clientSentence.isEmpty()) {
                    System.out.println("Socket closed by client");
                    connectionSocket.close();
                    closed = true;
                } else if (!clientSentence.isEmpty() && (clientSentence.contains(":"))) {
                    System.out.println("From Client: " + clientSentence);
                    String msgReceived[] = clientSentence.split(":");
                    String cmdCode = msgReceived[0];
                    String body = msgReceived[1];

                    /************* apresentação *************/
                    System.out.println("From Client: " + cmdCode + " " + body);
                    if (cmdCode.equals("200")) { // CONNECT
                        Peer buddy = new Peer(body, ip);
                        activedPeers.add(buddy);
                        nickName = body;
                        String msg = "HELLO: " + nickName + '\n';
                        outToClient.writeBytes(msg);
                        
                    /************ listagem ************/
                    } else if (cmdCode.equals("202")) { // LIST
                        String msg = "LIST" + '\n';
                        Iterator<Peer> ctrl = activedPeers.iterator();
                        while (ctrl.hasNext()) {
                            Peer p = ctrl.next();
//if (!p.isEqual(nickName)){
                            msg = msg + p.getNickName() + ":" + p.getIP().getHostAddress() + '\n';
//}
                        }
                        outToClient.writeBytes(msg);
                    } else if (cmdCode.equals("205")) { // CLOSE
                        String msg = "BYE" + '\n';
                        System.out.println("Socket closed nicely");
                        outToClient.writeBytes(msg);
                        connectionSocket.close();
                        closed = true;
                    }
                }
            } while (!closed);
        }
    }
}
